package com.rgp.apipassenger.interceptor;

import com.rgp.internalcommon.common.RedisPrefixConstant;
import com.rgp.internalcommon.common.CommonStatusEnum;
import com.rgp.internalcommon.dto.UserInfoDto;
import com.rgp.internalcommon.dto.ResponseResult;
import com.rgp.internalcommon.utils.JwtUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author nhp
 * @version 1.0
 * @description TODO
 * @date 2024-04-13 1:59
 */
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        UserInfoDto userInfoDto = null;

        //1.判断乘客是否携带token，若没有携带，则让乘客先登录
        String accessToken = request.getHeader("Authorization");
        if (StringUtils.isEmpty(accessToken)){
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.print(ResponseResult.fail(CommonStatusEnum.TOKEN_NOT_EXIST_ERROR));
            return false;
        }

        //2.乘客发起的请求携带了token，校验该token的合法性与时效性
        //2.1 解析该token，判断token能否被正常解析【如果可以被正常解析，说明该token就是本服务器所颁发,且未被篡改】
        try {
            userInfoDto = JwtUtils.paseToken(accessToken);
        }catch(Exception exception){
            response.getWriter().print(ResponseResult.fail(CommonStatusEnum.TOKEN_ERROR));
            response.setContentType("application/json;charset=utf-8");
            return false;
        }

        //2.2判断accessToken 与 redisToken之间的关系，如果此处判断无法通过，说明token已过期
        String redisToken = stringRedisTemplate.opsForValue().get(RedisPrefixConstant.PASSENGER_ACCESSTOKEN_PREFIX + userInfoDto.getUserPhone());
        if (StringUtils.isEmpty(redisToken) || !redisToken.equals(accessToken)){
            //redisToken为空，说明当前的accessToken过期了；如果两者不相等，说明已经当前手机号申请了新的token，当前accessToken作废
            response.getWriter().println(ResponseResult.fail(CommonStatusEnum.TOKEN_TIMEOUT_ERROR));
            response.setContentType("application/json;charset=utf-8");
            return false;
        }
        return true;
    }
}